/*
	This jukebox can play the raw files directly from the ascendancy .cob files. The usage is
	"jukebox cobfile.cob songfile.raw". You can see which files are inside a .cob file using
	readcob.
*/
#include "stdio.h"
#include "stdlib.h"
#include "readcob.c"
#include "stdbool.h"
#include "SDL/SDL.h"
#include "SDL/SDL_mixer.h"

int main(int argc, char** argv)
{
	if(argc<3)
		return 1;
	
	FILE *f = fopen(argv[1],"rb");	
	cob_file_table temp;
	temp=get_filetable(f);
	
	SDL_Event event;
  	int status, key;
  	bool quit = false;
	printf("playraw:::trying to play the file\n");
	
	//Let's initialize the SDL
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)<0)
	{
		printf("Could not initialize SDL");
	}

	SDL_Surface *screen;
	//Let's make a screen;
	screen = SDL_SetVideoMode(800, 600, 32,
                             SDL_HWSURFACE|SDL_DOUBLEBUF);	
	SDL_AudioSpec wav_spec;
	Uint32 wav_length;
	Uint8 *wav_buffer;
	
	//Format of the Ascendancy raw files:
	//8-Bit unsigned pcm
	int size;
	Uint8 *music;                       //Pointer to our music, in memory
	Mix_Chunk *musicchunk;				//The music, translated to the format SDL knows
	int audio_rate = 22050;             //Frequency of audio playback
	Uint16 audio_format = AUDIO_U8;     //Format of the audio we're playing
	int audio_channels = 1;             //2 channels = stereo
	int audio_buffers = 4096*2;         //Size of the audio buffers in memory

  	//Initialize SDL_mixer with our chosen audio settings
  	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0)
  	{
    	printf("Unable to initialize audio: %s\n", Mix_GetError());
    	return 1;
  	}

	//Now load the raw file and hope it works
	size=return_filesize_by_name(f,&temp,argv[2]);
	if(size<0)
	{
		printf("An error occured while loading the file!\n");
	}
	
	printf("Filesize in bytes:%d\n",size);
	
	//Mix_QuickLoad_RAW is quite dangerous. It does little to know checking,
	//so if you want to play the readme, it will do that. It will probably 
	//sound bad, though...
	music = return_file_by_name(f,&temp,argv[2]);
	musicchunk = Mix_QuickLoad_RAW(music, size);
	
	//-1 means "play on the first free channel"
	Mix_PlayChannel(-1, musicchunk, 0);

	while ( !quit ) {
    	status = SDL_WaitEvent(&event);     //wait indefinitely for an event to occur
                                        //event will be removed from event queue
    	if ( !status ) {                    //Error has occured while waiting
        	printf("SDL_WaitEvent error: %s\n", SDL_GetError());
			quit = true;
        	break;
    	}
    
    	switch(event.type) {
      		case SDL_QUIT:
				quit = true;
			break;	
      		case SDL_KEYDOWN:
				key = event.key.keysym.sym;
				if ( key == SDLK_ESCAPE )      //quit if 'ESC' pressed
        	  		quit = true;
			break;
    	} 
    SDL_Delay ( 100 );			//give up some cpu time for others
  	} //while ( !quit )			//quit may be set to true when 'ESC' is pressed 
  
  
  	Mix_CloseAudio();
	return 0;		
}
